+<template>
  <a-row :gutter="18" style="margin: 10px;">
    <a-col :md="5" :sm="24">
      <a-card :bordered="false">
        <div style="background: #fff;padding-left:16px;height: 100%; margin-top: 5px">
          <!-- <a-input-search @search="onSearch" style="width:100%;margin-top: 10px" placeholder="请输入部门名称"/> -->
          <!-- 树-->

          <template >
            <!--组织机构-->
            <a-tree
              v-if="departTree && departTree.length"
              showLine
              :selectedKeys="selectedKeys"
              :replace-fields="{children: 'children',
                                key: 'id',
                                title: 'categoryName',}"
              :checkStrictly="true"
              @select="onSelect"
              :dropdownStyle="{maxHeight:'200px',overflow:'auto'}"
              :treeData="departTree"
              defaultExpandAll
            />
          </template>
        </div>
      </a-card>
    </a-col>
    <a-col :md="19" :sm="24">
      <a-card :bordered="false">
        <div class="table-page-search-wrapper">
          <!-- 搜索区域 -->
          <a-row :gutter="10" style="margin-bottom: 20px;">
            <a-col :md="7" :sm="24" style="background: #36A9CE; box-shadow: 3px 3px 3px #ccc;">
              <div>
                <p style="font-size: 16px; font-weight: 800; padding: 10px; margin: 0px;">库存总量（行政类库存量+业务类库存量）</p>
                <p style="font-size: 24px; font-weight: 800; display: flex; justify-content: center; color: #fff;">{{ amounts }}</p>
              </div>
            </a-col>
            <a-col :md="7" :offset="1" :sm="24" style="background: #D0E17D; box-shadow: 3px 3px 3px #ccc;">
              <div>
                <p style="font-size: 16px; font-weight: 800; padding: 10px;  margin: 0px;">行政类库存量</p>
                <p style="font-size: 24px; font-weight: 800; display: flex; justify-content: center; color: #fff;">{{ administrative }}</p>
              </div>
            </a-col>
            <a-col :md="7" :offset="1" :sm="24" style="background: #EF5AA1; box-shadow: 3px 3px 3px #ccc;">
              <div>
                <p style="font-size: 16px; font-weight: 800; padding: 10px;  margin: 0px;">业务类库存量</p>
                <p style="font-size: 24px; font-weight: 800; display: flex; justify-content: center; color: #fff;">{{ business }}</p>
              </div>
            </a-col>
          </a-row>
          <a-form layout="inline">
            <a-row :gutter="10">
              <a-col :md="8" :sm="24">
                <a-form-item label="仓库名称" style="margin-left:8px">
                  <a-select
                    v-model="queryParam.storehouseId"
                    placeholder="请选择仓库"
                    :showSearch="true"
                    :allowClear="true"
                    @change="storehouseChange"
                    :filterOption="filterOption"
                    :getPopupContainer="triggerNode => {return triggerNode.parentNode}"
                  >
                    <a-select-option v-for="item in foldWarehouseList" :key="item.id" :value="item.id">{{ item.categoryName }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item
                  label="物料名称"
                  style="margin-left:8px"
                  :labelCol="{
                    xs: { span: 24 },
                    sm: { span: 5 },
                  }"
                  :wrapperCol="{
                    xs: { span: 24 },
                    sm: { span: 12 },
                  }"
                >
                  <select-material-input v-model="queryParam.materialName" :materialFlag="false"/>
                </a-form-item>
              </a-col>
              <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                <a-col :md="6" :sm="24">
                  <a-button type="primary" @click="searchQuery" icon="search" style="margin-left: 18px">查询</a-button>
                  <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
                </a-col>
              </span>
            </a-row>
          </a-form>
        </div>
        <a-button
          :loading="exportLoading"
          type="primary"
          icon="download"
          @click="handleExportXls('实时仓库物料一览表' + moment().format('YYYY-MM-DD-HH:mm:ss'))"
          :disabled="false"
          style="margin-bottom: 16px;"
        >导出
        </a-button>
        <!-- table区域-begin -->
        <div>
          <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
            <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
            <a style="margin-left: 24px" @click="onClearSelected">清空</a>
          </div>
          <a-table
            ref="table"
            size="middle"
            :scroll="{x:true}"
            bordered
            rowKey="id"
            :components="draggableComponent"
            :columns="columns"
            :dataSource="dataTreeList"
            :pagination="ipagination"
            :loading="loading"
            :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
            @change="handleTableChange">
            <template slot="provision" slot-scope="text,record">
              <span>{{record.provisionBroad_dictText && record.provisionSmall_dictText? record.provisionBroad_dictText + '-' + record.provisionSmall_dictText: '' }}</span>
            </template>

            <span slot="action" slot-scope="text, record">
              <a @click="handleEdit(record)">编辑</a>

              <a-divider type="vertical"/>

              <a-dropdown>
                <a class="ant-dropdown-link">
                  更多 <a-icon type="down"/>
                </a>
                <a-menu slot="overlay">
                  <a-menu-item>
                    <a href="javascript:;" @click="handleDeptRole(record)">分配部门角色</a>
                  </a-menu-item>

                  <a-menu-item>
                    <a href="javascript:;" @click="handleDetail(record)">用户详情</a>
                  </a-menu-item>
                </a-menu>
              </a-dropdown>
            </span>

          </a-table>
        </div>
      </a-card>
    </a-col>
  </a-row>
</template>
<script>
  import { searchByKeywords } from '@/api/api'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { getAction, downFile } from '@/api/manage'
  import SelectMaterialInput from '@/views/scy/components/SelectMaterialInput'
  import moment from 'moment';
  export default {
    name: 'ErpPurchaseWarehouse',
    mixins: [JeecgListMixin],
    components: {
      SelectMaterialInput
    },
    data() {
      return {
        moment,
        ipagination: {
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30', '50', '100', '200'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        currentDeptId: '',
        loading: false,
        disable: true,
        visible: false,
        departTree: [],
        checkedKeys: [],
        selectedKeys: [],
        form: this.$form.createForm(this),
        dataTreeList: [],
        columns: [
          {
            title: '序号',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: 'center',
            customRender: function (t, r, index) {
              return parseInt(index) + 1;
            }
          },
          {
            title: '仓库名称',
            align: 'center',
            width: 200,
            dataIndex: 'storehouseId_dictText'
          },
          {
            title: '物料类型',
            align: 'center',
            width: 200,
            dataIndex: 'provision',
            scopedSlots: { customRender: 'provision' }
          },
          {
            title: '物料编号',
            align: 'center',
            width: 200,
            dataIndex: 'materialBillId'
          },
          {
            title: '物料名称',
            align: 'center',
            width: 200,
            dataIndex: 'materialName_dictText'
          },
          {
            title: '品牌',
            align: 'center',
            width: 200,
            dataIndex: 'brand'
          },
          {
            title: '规格型号',
            align: 'center',
            width: 200,
            dataIndex: 'specification'
          },
          {
            title: '数量',
            align: 'center',
            width: 100,
            dataIndex: 'amount'
          },
          {
            title: '单位',
            align: 'center',
            width: 200,
            dataIndex: 'unit_dictText'
          }
        ],
        url: {
          list: '/api/erp/purchase/material/erpMaterialCategory/list',
          queryCountNum: '/api/erp/purchase/storehouse/erpPurchaseWarehouse/queryCountNum',
          warehouse: '/api/erp/purchase/storehouse/erpPurchaseWarehouse/list',
          exportXlsUrl: '/api/erp/purchase/storehouse/erpPurchaseWarehouse/exportXls',
          queryByStorehouseManager: '/api/erp/purchase/storehouse/erpStorehouseBase/queryByStorehouseManager'
        },
         administrative: 0,
         amounts: 0,
         business: 0,
         foldWarehouseList: [],
         params: {
          applicant: null,
          provisionBroad: null,
          provisionSmall: null,
          storehouseId: null,
          materialName: null,
          pageNo: 1,
          pageSize: 10
        }
      }
    },
    computed: {
      userInfo() {
        return this.$store.getters.userInfo
      }
    },
    methods: {
      searchQuery() {
        this.params.storehouseId = this.queryParam.storehouseId
        if (!!this.queryParam.materialName) {
          this.params.materialName = this.queryParam.materialName
        }
        this.ipagination.current = 1
        this.params.pageNo = this.ipagination.current
        this.params.pageSize = this.ipagination.pageSize
        this.warehouseList()
      },
      searchReset() {
        this.queryParam = {}
        this.params.storehouseId = null
        this.params.materialName = null
        this.ipagination.current = 1
        this.params.pageNo = this.ipagination.current
        this.params.pageSize = this.ipagination.pageSize
        this.warehouseList()
      },
      handleExportXls(fileName) {
        this.exportLoading = true
        if (!fileName || typeof fileName !== 'string') {
          fileName = '导出文件'
        }
        let param = this.getQueryParams()
        if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
          param['selections'] = this.selectedRowKeys.join(',')
        }
        console.log('导出参数', param)
        downFile(this.url.exportXlsUrl, this.params).then(data => {
          if (!data) {
            this.$message.warning('文件下载失败')
            return
          }
          if (typeof window.navigator.msSaveBlob !== 'undefined') {
            window.navigator.msSaveBlob(
              new Blob([data], {
                type: 'application/vnd.ms-excel'
              }),
              fileName + '.xls'
            )
          } else {
            let url = window.URL.createObjectURL(
              new Blob([data], {
                type: 'application/vnd.ms-excel'
              })
            )
            let link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', fileName + '.xls')
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link) // 下载完成移除元素
            window.URL.revokeObjectURL(url) // 释放掉blob对象
          }
        }).finally(() => {
          this.exportLoading = false
        })
      },
      filterOption(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },
      findFoldApplicant() {
        const that = this
        getAction(this.url.queryByStorehouseManager, { storehouseManager: this.userInfo.empId }).then((res) => {
          if (res.success) {
            that.foldWarehouseList = []
            res.result.forEach((res) => {
              that.foldWarehouseList.push({ 'id': res.id, 'categoryName': res.storehouseName })
            })
          } else {
            that.$message.warning(res.message)
          }
        })
      },
      countNum () {
        getAction(this.url.queryCountNum, { storehouseManager: this.userInfo.empId }).then(res => {
          if (res.code === 200 && res.result) {
            this.administrative = res.result['administrative']
            this.amounts = res.result['amounts']
            this.business = res.result['business']
          }
        })
      },
      loadData() {
        this.refresh();
      },
      loadTree() {
        var that = this
        that.departTree = []
        getAction(this.url.list).then(res => {
        if (res.code === 200 && res.result) {
          that.departTree = res.result.records
        }
      })
      },
      refresh() {
        this.loadTree()
      },
      storehouseChange(data) {
        if (!data) {
          this.$set(this.queryParam, 'storehouseId', undefined)
        }
      },
      onSearch(value) {
        let that = this
        if (value) {
          searchByKeywords({ keyWord: value, myDeptSearch: '1' }).then((res) => {
            if (res.success) {
              that.departTree = []
              for (let i = 0; i < res.result.length; i++) {
                let temp = res.result[i]
                that.departTree.push(temp)
              }
            } else {
              that.$message.warning(res.message)
            }
          })
        } else {
          that.loadTree()
        }
      },
      onSelect(selectedKeys, e) {
        if (this.selectedKeys[0] !== selectedKeys[0]) {
          this.selectedKeys = [selectedKeys[0]];
          if (e.node.pos.length == 3) {
            this.params.provisionBroad = this.selectedKeys[0]
            this.params.provisionSmall = null
          } else if (e.node.pos.length > 3) {
            this.params.provisionSmall = this.selectedKeys[0]
            this.params.provisionBroad = null
          }
          this.warehouseList()
        }
      },

      warehouseList () {
        this.loading = true
        this.params.storehouseManager = this.userInfo.empId
        this.params.column = 'amount'
        this.params.order = 'desc'
        getAction(this.url.warehouse, this.params).then(res => {
          if (res.code === 200 && res.result) {
            this.dataTreeList = res.result.records || res.result
            if (res.result.total) {
              this.ipagination.total = res.result.total
            } else {
              this.ipagination.total = 0
            }
            // 判断是否当前页没有数据且不为第一页
            if (this.dataTreeList.length == 0 && this.ipagination.current != 1) {
              this.ipagination.current = this.ipagination.current - 1
              this.loadData(this.ipagination.current - 1);
            }
          } else {
            this.dataTreeList = [];
            this.ipagination.total = 0
          }
          if (res.code === 510) {
            this.$message.warning(res.message)
          }
        }).finally(() => {
          this.loading = false
        })
      },
      handleTableChange(pagination, filters, sorter) {
        // 分页、排序、筛选变化时触发
        console.log('pagination', pagination)
        this.ipagination = pagination
        this.params.pageNo = this.ipagination.current
        this.params.pageSize = this.ipagination.pageSize
        this.warehouseList()
      }
    },
    created() {
      this.countNum() // 查询数量
      this.findFoldApplicant()//根据单位查询仓库
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less'
</style>
